<script setup lang="ts">
import page from "./page.vue";
import catalogueForm from "./catalogueForm.vue";
import pageForm from "./pageForm.vue";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps, pageFormItemProps } from "./utils/types";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, onMounted, h } from "vue";
import { deviceDetection } from "@pureadmin/utils";

import { ArrowLeft, CirclePlus, MoreFilled } from "@element-plus/icons-vue";

const emit = defineEmits(["save"]);

// 设置路由权限弹窗
const drawer = ref(false);
const authPageRouter = ref([]);

// 打开弹窗
function openDrawer(auth_pages) {
  if (auth_pages) authPageRouter.value = JSON.parse(auth_pages);
  drawer.value = true;
}

// 关闭弹窗
function closeDrawer() {
  drawer.value = false;
}

function removeEmptyChildren(data) {
  // 处理数组情况
  if (Array.isArray(data)) {
    // 先递归处理每个元素
    const processedArray = data.map(item => removeEmptyChildren(item));
    // 然后过滤掉null值（被完全删除的节点）
    return processedArray.filter(item => item !== null);
  }

  // 处理对象情况
  if (typeof data === "object" && data !== null) {
    // 如果有children属性
    if ("children" in data) {
      // 如果是null或空数组，直接删除children属性
      if (
        data.children === null ||
        (Array.isArray(data.children) && data.children.length === 0)
      ) {
        delete data.children;
      }
      // 否则递归处理children
      else {
        data.children = removeEmptyChildren(data.children);
        // 处理完后再次检查是否变成空数组
        if (Array.isArray(data.children) && data.children.length === 0) {
          delete data.children;
        }
      }
    }

    // 检查对象是否有其他有效属性
    const keys = Object.keys(data);
    const hasValidProperties = keys.some(key => {
      if (key === "children") return false;
      return data[key] !== null && data[key] !== undefined;
    });

    // 如果没有有效属性且没有children，则删除整个节点
    if (!hasValidProperties && !("children" in data)) {
      return null;
    }

    return data;
  }

  // 其他类型直接返回
  return data;
}

// 保存
function saveBtnClick() {
  let pageRouter = JSON.parse(JSON.stringify(authPageRouter.value));
  const newArr = removeEmptyChildren(pageRouter);
  emit("save", newArr);
  drawer.value = false;
}

const pageRef = ref();

const chooseRouter = ref();

// 添加目录或页面
function addPages() {
  pageRef.value.openDialog();
}

// 对数据操作
function handleCommand(row, e) {
  if (e == "add") handleAdd(row);
  if (e == "edit") handleSave(row);
  else if (e == "delete") handleDelete(row);
}

// 其下新增操作
function handleAdd(row) {
  chooseRouter.value = row;
  pageRef.value.openDialog(row);
}

const catalogueFormRef = ref()
const pageFormRef = ref()
// 编辑操作
function handleSave(row) {
  if (row.meta.type == "menu") { // 目录
    addDialog({
      title: '编辑目录',
      props: {
        formInline: {
          path: row?.path ?? "",
          title: row?.meta.title ?? "",
          icon: row?.meta.icon ?? "",
          rank: row?.meta.rank ?? 1
        }
      },
      width: "440px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(catalogueForm, { ref: catalogueFormRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = catalogueFormRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        FormRef.validate(valid => {
          if (valid) {
            for (let i = 0; i < authPageRouter.value.length; i++) {
              if (row.path == authPageRouter.value[i].path) {
                authPageRouter.value[i].path = curData.path
                authPageRouter.value[i].meta.icon = curData.icon
                authPageRouter.value[i].meta.title = curData.title
                authPageRouter.value[i].meta.rank = Number(curData.rank)
              }
            }
            done(); // 关闭弹窗
          }
        });
      }
    });
  } else { // 页面
    addDialog({
      title: '编辑目录',
      props: {
        formInline: {
          title: row?.meta.title ?? "",
        }
      },
      width: "440px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(pageForm, { ref: pageFormRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = pageFormRef.value.getRef();
        const curData = options.props.formInline as pageFormItemProps;
        FormRef.validate(valid => {
          if (valid) {
            for (let i = 0; i < authPageRouter.value.length; i++) {
              if (row.path == authPageRouter.value[i].path) authPageRouter.value[i].meta.title = curData.title
              if (authPageRouter.value[i].children) {
                for (let a = 0; a < authPageRouter.value[i].children.length; a++) {
                  if (row.path == authPageRouter.value[i].children[a].path) authPageRouter.value[i].children[a].meta.title = curData.title
                }
              }
            }
            done(); // 关闭弹窗
          }
        });
      }
    });
  }
}

// 操作目录回调
function handleCatalogue(form) {
  // 新增
  authPageRouter.value.push({
    path: form.path,
    meta: {
      icon: form.icon,
      title: form.title,
      type: "menu"
    },
    children: []
  });
}

// 操作页面回调
function handlePage(form) {
  if (chooseRouter.value) {
    // 其下新增
    for (let i = 0; i < authPageRouter.value.length; i++) {
      if (chooseRouter.value.path == authPageRouter.value[i].path) {
        if (authPageRouter.value[i].children) authPageRouter.value[i].children.push(form.router);
        else authPageRouter.value[i].children = [form.router];
      }
    }
  } else {
    // 新增
    authPageRouter.value.push(form.router);
  }
}

// 删除操作
function handleDelete(row) {
  ElMessageBox.confirm(
    `确定删除该${row.children ? "目录" : "页面路由及对应的页面元素权限"}`,
    "重要提示",
    { type: "warning" }
  )
    .then(() => {
      if (row.children && row.children.length) {
        message("删除失败，请先删除该目录下所有页面", { type: "error" });
      } else {
        let pageRouter = authPageRouter.value;
        if (row.children) {
          for (let i = 0; i < pageRouter.length; i++) {
            if (row.path == pageRouter[i].path) pageRouter.splice(i, 1);
          }
        } else {
          for (let i = 0; i < pageRouter.length; i++) {
            if (row.path == pageRouter[i].path) pageRouter.splice(i, 1);
            if (pageRouter[i].children.length) {
              for (let a = 0; a < pageRouter[i].children.length; a++) {
                if (row.path == pageRouter[i].children[a].path) pageRouter[i].children.splice(a, 1);
              }
            }
          }
        }
        authPageRouter.value = pageRouter;
        message("删除成功", { type: "success" });
      }
    })
    .catch(() => {});
}

defineExpose({ openDrawer });
</script>

<template>
  <div>
    <el-drawer
      v-model="drawer"
      size="100%"
      :with-header="false"
      direction="rtl"
    >
      <div class="w-full h-full">
        <div class="header">
          <div class="flex items-center">
            <div
              class="flex items-center"
              style="cursor: pointer"
              @click="closeDrawer"
            >
              <el-icon><ArrowLeft /></el-icon>
              返回
            </div>
            <div class="title">角色路由权限配置</div>
          </div>
          <el-button type="primary" @click="saveBtnClick"> 保存 </el-button>
        </div>

        <div class="flex justify-between">
          <div style="flex: 1">
            <div class="flex items-center justify-between">
              <div class="bt flex items-center">
                <span></span>
                <b>路由编排区</b>
              </div>
              <div class="flex items-center">
                <el-icon size="18" style="cursor: pointer" @click="addPages()"
                  ><CirclePlus
                /></el-icon>
              </div>
            </div>

            <div class="content">
              <el-scrollbar
                height="calc(100vh - 117px)"
                style="background-color: #f5f5f5; border-radius: 6px"
              >
                <el-tree
                  class="m-[20px]"
                  :data="authPageRouter"
                  default-expand-all
                  node-key="id"
                  #default="{ data }"
                  :draggable="false"
                >
                  <div class="w-full flex items-center justify-between">
                    <div>
                      <el-button
                        link
                        :icon="useRenderIcon(data.meta.icon)"
                      ></el-button>
                      {{ data.meta.title }}
                    </div>
                    <el-dropdown @command="handleCommand(data, $event)">
                      <el-icon><MoreFilled /></el-icon>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item
                            v-if="data.meta.type == 'menu'"
                            command="add"
                            >其下新增</el-dropdown-item
                          >
                          <el-dropdown-item command="edit"
                            >编辑</el-dropdown-item
                          >
                          <el-dropdown-item divided command="delete"
                            >删除</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </el-tree>
              </el-scrollbar>
            </div>
          </div>

          <div class="w-[32%] ml-[30px]">
            <div class="bt flex items-center">
              <span></span>
              <b>路由规则结果</b>
            </div>

            <div class="content">
              <el-scrollbar
                height="calc(100vh - 117px)"
                style="background-color: #f5f5f5; border-radius: 6px"
              >
                <pre class="p-[20px]" style="color: #000000; font-size: 13px">{{
                  authPageRouter
                }}</pre>
              </el-scrollbar>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <page ref="pageRef" @catalogue="handleCatalogue" @page="handlePage"></page>
  </div>
</template>

<style lang="scss" scoped>
.header {
  padding-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .title {
    font-weight: bold;
    margin-left: 16px;
    padding-left: 16px;
    position: relative;

    &::after {
      content: "";
      width: 1px;
      height: 13px;
      background-color: #000000;
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }
}

.bt {
  span {
    display: block;
    width: 6px;
    height: 18px;
    background-color: var(--pure-theme-menu-active-before);
    margin-right: 5px;
  }
}

.content {
  margin-top: 16px;
}

:deep(.el-tree-node__content) {
  height: 46px !important;
  border-bottom: 5px solid #f5f5f5;
  padding: 20px;
}
</style>
